package com.itheima.controller;


import com.itheima.dto.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderSettingService;
import com.itheima.utils.POIUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ordersetting")
@ResponseBody
public class OrderSettingController {

    @Autowired
    private OrderSettingService orderSettingService;
    @Value("${health.path}")
    private String basePath;

    /**
     * 添加或编辑预约设置
     * @return
     */
    @PostMapping("/editNumberByDate")
    public Result editNumberByDate(@RequestBody OrderSetting orderSetting) {
        try {
            orderSettingService.editNumberByDate(orderSetting);
            return Result.success("预约设置成功");
        } catch (Exception e) {
            return Result.error("预约设置失败");
        }
    }


    /**
     * 查询给定月份预约设置--吴登晖
     * @param date 时间数值，前端传值类型String，实体类设置自动转换为Date类型
     * @return 返回结果
     */
    @PostMapping("/getOrderSettingByMonth")
    public Result getOrderSettingByMonth(@Param("orderDate") String date){
        List<Map> orderSettingByMonth = orderSettingService.getOrderSettingByMonth(date);
        return Result.success(orderSettingByMonth,"获取预约设置数据成功~");
    }



    //批量导入预约设置,文件上传
    @PostMapping("/upload")
    public Result upload(MultipartFile excelFile, HttpServletResponse response, HttpSession session){
        //获取上传文件的名称
        String fileName = excelFile.getOriginalFilename();
        try {
            List<String[]> strings = POIUtils.readExcel(excelFile);
            FileWriter fileWriter = new FileWriter(basePath+fileName);
            fileWriter.write(String.valueOf(strings),0,strings.size());
            fileWriter.close();
            return Result.success("上传成功!");
        } catch (IOException e) {
            return Result.error("上传失败!");
        }
    }
}
